package com.xrit.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.pojo.Permission;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.pojo.User;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Set;
/*
实现UserDetailsService,将查询到的数据交给springsecurity去管理
 */
public class UserSecurity implements UserDetailsService {
    /*
    远程调用
     */
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //2,调用查询方法
        User user = userService.findByUserName(username);
        //3,new List<Grant...> 集合
        ArrayList<GrantedAuthority> authorityArrayList = new ArrayList<>();
        SimpleGrantedAuthority simpleGrantedAuthority=null;
        if(user!=null) {
            //4,从user中取出角色并遍历集合
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                //4.1 将角色添加到list中,new SimpleGrantedAuthority(GrantedAuthority的实现类)
                 simpleGrantedAuthority = new SimpleGrantedAuthority(role.getKeyword());
                 authorityArrayList.add(simpleGrantedAuthority);
                 //5,从role中取出权限并遍历集合
                Set<Permission> permissions = role.getPermissions();
                for (Permission permission : permissions) {
                    //5.1,将权限添加到list集合中,new SimpleGrantedAuthority
                    simpleGrantedAuthority=new SimpleGrantedAuthority(permission.getKeyword());
                    authorityArrayList.add(simpleGrantedAuthority);
                }
            }
            //1,因为我们需要将数据返回 new User(UserDetails 的实现类)
            return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorityArrayList);
        }
        //限制访问
        return null;
    }
}
